<?php
/**
 * api模块
 */

include 'includes/fun.global.php';
include_once(SYSTEM_ROOT . "fun.admin.php");
@header('Content-Type: application/json; charset=UTF-8');

use lib\supply\Order;
use lib\supply\xiaochu;

switch ($_QET['act']) {
    case 'ip':
        dies(1, userip());
        break;
    case 'operation':
        admin::operation($_QET);
        break;
    case 'WebsiteData': #获取网站基础数据
        dier(['code' => 1, 'msg' => '数据获取成功', 'data' => [
            'sitename' => $conf['sitename'], //网站名称
            'kfqq' => $conf['kfqq'], //客服QQ
            'notice_top' => base64_decode($conf['notice_top']), //首页公告
            'notice_check' => base64_decode($conf['notice_check']), //查单公告
            'notice_bottom' => base64_decode($conf['notice_bottom']), //底部公告
            'notice_user' => base64_decode($conf['notice_user']), //分站后台公告
            'PopupNotice' => base64_decode($conf['PopupNotice']), //首页弹窗公告
            'currency' => $conf['currency'], //货币名称
        ], 'time' => time()]);
        break;
    case 'DockingGoodsLog': //商品详情api
        $User = xiaochu::verify($_QET);
        dier(xiaochu::GoodsLog($User, $_QET['gid']));
        break;
    case 'DockingGoodsList': //获取商品列表api
        $User = xiaochu::verify($_QET);
        dier(xiaochu::GoodsList());
        break;
    case 'Docking_buy': //对接下单api
        $User = xiaochu::verify($_QET);
        xiaochu::Buy($User, $_QET);
        break;
    case 'DockingQuery': //订单查询api
        $User = xiaochu::verify($_QET);
        xiaochu::QueryApi($User, $_QET);
        break;
    case 'Docking_goods':
        $Docking = new Docking();
        $verify = $Docking->verify($_QET);
        if ($verify['code'] == 1) {
            $gid = (int)$_QET['gid'];
            $data = $DB->get_row("SELECT * FROM `sky_goods` WHERE `gid` = $gid LIMIT 1");
            $price = price::price_uid($verify['data']['grade'], $data['profits'], $data['money'], $data['custom']);
            unset($data['profits'], $data['money']);
            $price['price'] = (float)$price['price'] / $data['quantity'];
            $price['state'] = $data['state'];
            dier(['code' => 1, 'msg' => '获取成功!', 'data' => $price]);
        } else dies(-1, '验证失败');
        break;
    case 'UserMoneyApi': //用户加款/扣钱
        if (empty((string)$_QET['token']) || empty((int)$_QET['uid']) || empty((int)$_QET['type']) || empty((float)$_QET['money'])) dies(-1, '请填写完整！');
        if ((string)$_QET['token'] <> $conf['secret']) dies(-1, 'API对接密钥有误！');
        $uid = (int)$_QET['uid'];
        $money = (float)$_QET['money'];
        $dr = $DB->get_row("SELECT money FROM `sky_user` WHERE `id` = $uid LIMIT 1");
        if (!$dr) dies(-1, '用户不存在！');
        switch ((int)$_QET['type']) {
            case 1: #充值
                $m = $dr['money'] + $money;
                $re = $DB->query("UPDATE `sky_user` SET `money`= $m WHERE (`id`='$uid')");
                break;
            case 2: #扣款
                $m = $dr['money'] - $money;
                if ($m < 0) dies(-1, '用户余额低于0,无法扣款！');
                $re = $DB->query("UPDATE `sky_user` SET `money`= $m WHERE (`id`='$uid')");
                break;
        }
        if ($re) {
            $msg = '成功通过api为用户(' . $uid . ')' . ($_QET['type'] == 1 ? '加款' : '扣款') . $money . '元,操作后余额为:' . $m . '元!';
            userlog(($_QET['type'] == 1 ? '后台加款' : '后台扣款'), $msg, $uid, $money);
            dies(1, $msg);
        } else dies(-1, ($_QET['type'] == 1 ? '加款' : '扣款') . '失败！');
        break;
    case 'OrdersTesting': //漏单监控(目前只支持易支付！)
        price_monitoring::pay_order();
        break;
    case 'SubmitOrder': //订单队列监控,直接监控既可，无需验证
        //if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        if (empty((int)$_QET['num'])) {
            $_QET['num'] = 2;
        }
        if ($_QET['num'] > 10) dies(-1, '最多一次监控提交10份订单！');
        dier(Order::SubmitOrderQueue(false, (int)$_QET['num']));
        break;
    case 'SqlBackupsRecovery':
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        include_once(SYSTEM_ROOT . "extend/SqlBackups.php");
        $re = \extend\SqlBackups::SqlBackupsRecovery($_QET['name'], $_QET['page'], $_QET['limit']);
        if ($re['code'] <> 1) dies(-1, '恢复失败！');
        dier($re);
        break;
    case 'SqlBackupsDownload':
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        include_once(SYSTEM_ROOT . "extend/SqlBackups.php");
        dier(\extend\SqlBackups::SqlBackupsDownload($_QET['name'], $_QET['date']));
        break;
    case 'SqlBackupsDel':
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        include_once(SYSTEM_ROOT . "extend/SqlBackups.php");
        \extend\SqlBackups::SqlBackupsDel($_QET['name']);
        break;
    case 'SqlBackupsList':
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        include_once(SYSTEM_ROOT . "extend/SqlBackups.php");
        \extend\SqlBackups::SqlBackupsList($_GET);
        break;
    case 'SqlBackupsUpdate':
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        include_once(SYSTEM_ROOT . "extend/SqlBackups.php");
        \extend\SqlBackups::SqlBackupsUpdate($_QET['name']);
        break;
    case 'SqlBackupsDownloadLocal':
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        include_once(SYSTEM_ROOT . "extend/SqlBackups.php");
        \extend\SqlBackups::SqlBackupsDownloadLocal();
        break;
    case 'SqlBackups':
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        include_once(SYSTEM_ROOT . "extend/SqlBackups.php");
        $re = \extend\SqlBackups::MysqlBackups();
        if ($re['code'] <> 1) dies(-1, '备份失败！');
        dier($re);
        break;
    case 'OrderList': //取出订单列表
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        if (empty((int)$_QET['state'])) dies(-1, '请将需要取出的订单类型填写完整!<br>类型：1成功，2待处理，3异常，4正在处理，5退款,6售后维权,7已评价');
        if (empty((int)$_QET['limit'])) dies(-1, '请将需要取出的数量填写完整!');
        $DB = \Medoo\DB\SQL::DB();
        $Res = $DB->select('order', ['id', 'order', 'trade_no', 'uid', 'ip', 'input', 'state', 'num', 'return', 'gid', 'order_id', 'money', 'payment', 'take', 'price', 'user_rmb', 'remark', 'finishtime(endtime)', 'addtitm(addtime)'], ['state' => $_QET['state'], 'ORDER' => [
            'id' => 'DESC',
        ], 'LIMIT' => $_QET['limit']]);
        if (!$Res) dies(-1, '订单列表获取失败！');
        dier([
            'code' => 1,
            'msg' => '订单数据获取成功！',
            'class' => '类型(state)：1成功，2待处理，3异常，4正在处理，5退款,6售后维权,7已评价',
            'data' => $Res,
        ]);
        break;
    case 'OrderSet': //修改订单状态,可修改订单状态,返回内容,货源余额,订单备注
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        if (empty((int)$_QET['state'])) dies(-1, '请将订单修改后的状态填写完整:state！<br>类型：1成功，2待处理，3异常，4正在处理，5退款,6售后维权,7已评价');
        if (empty($_QET['remark'])) dies(-1, '请将订单备注填写完整:remark!');
        if (empty((float)$_QET['user_rmb'])) $_QET['user_rmb'] = 0;
        if (empty($_QET['order_id'])) dies(-1, '请将货源订单号填写完整:order_id!');
        if (empty($_QET['return'])) dies(-1, '请将对接返回信息填写完整:return!');
        if (empty($_QET['order'])) dies(-1, '请将订单号填写完整:order!');

        $DB = \Medoo\DB\SQL::DB();
        $Res = $DB->update('order', [
            'state' => $_QET['state'],
            'remark' => $_QET['remark'],
            'user_rmb' => $_QET['user_rmb'],
            'return' => $_QET['return'],
            'order_id' => $_QET['order_id'],
        ], [
            'order' => $_QET['order'],
        ]);
        if ($Res) {
            dies(1, '订单[' . $_QET['order'] . ']状态修改成功');
        } else dies(-1, '修改订单状态失败！.' . $DB->error());
        break;
    case 'Supervisory': //商品价格轮询监控
        $Flie = ROOT . 'includes/lib/soft/controller/CommodityPriceMonitoring/index.php';
        if (!file_exists($Flie)) dies(1, '价格接口插件未安装！');
        if ($conf['secret'] <> $_QET['token']) dies(-1, 'API对接密钥有误！');
        $DB = \Medoo\DB\SQL::DB();

        $Array = file_get_contents(ROOT . "/assets/log/phpshop.log");
        $Array = explode('|', $Array);
        //unset($Array[count($Array) - 1]);
        $Res = $DB->select('goods', '*', [
            'gid[!]' => $Array,
            'LIMIT' => 1,
        ]);
        $Goods = $Res[0];
        if (in_array(5, json_decode($Goods['method'], TRUE))) {
            $DB = new DB($dbconfig['host'], $dbconfig['user'], $dbconfig['pwd'], $dbconfig['dbname'], $dbconfig['port']);
            include_once $Flie;
            $state_gid = \lib\CommodityPriceMonitoring::origin($Goods, 2);
            if ($state_gid) {
                @file_put_contents(ROOT . "/assets/log/phpshop.log", $Goods['gid'] . '|', FILE_APPEND);
                dies(1, '商品' . $Goods['name'] . '监控成功！');
            } else dies(-1, '商品' . $Goods['name'] . '监控失败！');
        } else
            unlink(ROOT . "/assets/log/phpshop.log");
        dies(-1, '无可监控商品咯,即将开始下一轮监控！');
        break;
    default:
        dies(-1, '403');
        break;
}